package com.bookmanger.controller;

import com.bookmanger.common.result.Result;
import com.bookmanger.service.IFileMapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import java.io.IOException;

/**
 * @folder 文件管理
 */
@RestController
@RequestMapping("/file")
public class FileMapController {

    @Autowired
    IFileMapService iFileMapService;

    /**
     * 上传文件
     * @param imageFile
     * @return
     * @throws IOException
     */
    @PostMapping("/image")
    public Result<String> uploadImage(@RequestParam("imageFile") MultipartFile imageFile) throws IOException {
        String[] path = {};
        return iFileMapService.UpdateFileMap(imageFile,path);
    }

    /**
     * 根据图片id获取图片
     * @param imageId
     * @return
     */
    @GetMapping("/image")
    public ResponseEntity<byte[]> getImage(@RequestParam String imageId){
        String imagePath = iFileMapService.getFilePathByID(imageId);
        String imageUrl = "http://8.134.139.46:8081" + imagePath;
//        request.getRequestDispatcher(imageUrl);
//        response.sendRedirect(imageUrl);
        RestTemplate restTemplate = new RestTemplate();
        byte[] image = restTemplate.getForObject(imageUrl, byte[].class);

        MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
        String contentType = fileTypeMap.getContentType(imagePath);

        return ResponseEntity.ok().contentType(MediaType.valueOf(contentType)).body(image);
    }
}
